import numpy as np
from  sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.neighbors import KNeighborsClassifier

def readFile(filename):
    x = []
    y = []
    with open(filename, "rb") as fp:
        while True:
            line = fp.readline().decode().strip() #去除前后空格
            print(line)
            if line:
                arr = line.split("\t")
                y.append(eval(arr[3]))
                for i in range(3):
                    arr[i] = eval(arr[i])
                x.append(arr[:3])
            else:
                print("===============end===============")
                break
    return np.array(x),np.array(y)

if __name__ == '__main__':
    x,y = readFile("datingTestSet.txt")
    #数据集划分
    x_train,x_test,y_train,y_test = train_test_split(x,y)
    #标准化
    transfer = MinMaxScaler()
    x_train = transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)     #按x_train的规则去归一化
    #模型训练
    estimate = KNeighborsClassifier(n_neighbors=5)
    estimate.fit(x_train, y_train)
    print(estimate.kneighbors(x_train,n_neighbors=5))
    #模型评估
    print("knn得分：\n",estimate.score(x_test, y_test))
    y_pred = estimate.predict(x_test)
    print("测试集的预测：\n",y_pred)
    print("对比测试集和预测集：\n",y_pred==y_test)
